<?php
/* This file is part of Mirasol CMS
   (C) 2011 by Alban Technologies. Written by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/login.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/db.php";

if ($login['username'] != "")
{
  header ("Location: ./");
  exit;
}

$connection = db_open ();

if (isset ($_POST['username']) && trim ($_POST['username']) != "")
{
  $username = mysql_real_escape_string (trim ($_POST['username']));
  $result = mysql_query ("SELECT passwd, salt FROM ".db_maketablename ($table_users)." WHERE username = '$username'");
  if (mysql_num_rows ($result) > 0)
    {
      $row = mysql_fetch_array ($result);
      
      if ($row['passwd'] == md5 ($_POST['passwd'].$row['salt']))
        {
          session_start ();
          $_SESSION['username'] = $row['username'];
          $_SESSION['passwd'] = $row['passwd'];
          setcookie ("username", $row['username'], time () + 60 * 60);
          setcookie ("passwd", $row['passwd'], time () + 60 * 60);
        }
      else
        {
          setcookie ("username", "", time () - 3600);
          setcookie ("passwd", "", time () - 3600);
          session_unregister ('username'); 
          session_unregister ('passwd');
        }
    }
  mysql_free_result ($result);
  
  header ("location: ./");
  exit;
}

db_close ($connection);

if ($loadsubpage == 1)
{
?>
<h1>Log in</h1>
      
<form method="post" action="./login.php">
  <table cellpadding="0" cellspacing="0" class="form">
    <tr>
      <td class="form"><strong>User name:</strong></td>
      <td class="formfield"><input type="text" name="username" maxlength="20" class="textfield" /></td>
    </tr>
    <tr>
      <td class="form"><strong>Password:</strong></td>
      <td class="formfield"><input type="password" name="passwd" class="textfield" /></td>
    </tr>
    <tr>
      <td colspan="2"><input type="submit" value="Login" class="button alignright" /></td>
    </tr>
  </table>
</form>
<?php
}
?>
